<template>
<div class="container w-screen-md h-screen-sm">
  <div class="row border border-black" style="height: 100%;">
    <div class="col overflow-auto p-0">
      <p class="text-center mt-3">聊天室公告</p>
      <div class="demo-collapse">
    <el-collapse v-model="activeName" accordion class="ml-1">
      <el-collapse-item v-for="(item,index) in noticeList" :key="index" :title="'公告'+(index+1)" :name="index">
        <div>
          <b>内容：</b>{{ item.notice_content }}
          <br><b>发布者：</b>{{ item.publisher_id }}
          <br> <b>发布时间：</b> <br>{{ item.publish_time }}
          <br><div class="pr-3 mb-2"><button v-if="admin_id==user_id" @click="deleteNoticeByID(item.notice_id)"
             class="btn btn-outline-dark btn-sm mx-auto float-right">删除</button></div>
        </div>
      </el-collapse-item>
    </el-collapse>
    <el-button  v-if="admin_id==user_id"
    @click="dialogVisible = true" class="btn btn-outline-dark w-100">添加公告</el-button >
        <el-dialog
          v-model="dialogVisible"
          title="添加公告"
          width="500"
        >
        <el-input
          v-model="notice.notice_content"
          style="width:100%"
          :autosize="{ minRows: 3, maxRows: 4 }"
          type="textarea"
          placeholder="请输入"
        />
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="addNoticeInChatroom">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

  </div>
    </div>
    <div class="col-8 p-0 border-x border-black">
        <p class="h-1/15 mb-0 text-center" style="font-size: 1.5em">{{ project_name }}
          <el-button v-if="user_id==admin_id" plain @click="open" class="btn btn-outline-dark mx-1" style="margin-top: 5px;float: right;">关闭聊天室</el-button>
          <button class="btn btn-outline-primary" @click="exitChatroom" style="margin-top: 2px;float: right;">退出聊天室</button>
        </p>
        <div class="h-2/3 overflow-auto border-y border-black"> 
          <div class="container">

              <ul>
                  <li v-for="(item,index) in messageListChatroom" :key="index">
                  
                  <div class="row">
                    <div class="col-sm-12 my-2">
                        <p class="text-center mb-2">{{ item.sendTime }}</p>
                        <div :class="isSelf(item.fromName)">
                          <div class="col-1 col-sm-1">
                            <el-avatar class="text-black bg-blue-300">{{ item.senderName }}</el-avatar>
                          </div>
                          <div class="d-flex align-items-center col-auto border rounded-pill">
                          <p class="m-0">{{ item.message }}</p>
                          </div>
                          </div>
                    </div>
                </div>
                  </li>
              </ul>
               
            </div>
        </div>
        <div class="flex h-1/4 justify-content-end rounded-bottom">
          <textarea @keyup.enter="sendMessageToChatroom()" class="flex form-control p-0" id="exampleFormControlTextarea1" v-model="inputMessage" rows="2"></textarea>
          <button type="button" @click="sendMessageToChatroom()" class="btn btn-outline-primary align-self-end m-3" style="position: absolute;">发送</button>
        </div>
    </div>
    <div class="col overflow-auto">
      <p class="text-center mt-3">聊天室成员列表</p>
        <ul class="list-group list-group-flush">
          <li v-for="(item,index) in userList" :key="index" class="list-group-item">
            {{ item.userID }} {{ item.userName }}</li>
            <li v-if="admin_id==user_id" class="list-group-item">
              <button @click="inviteWindow=true" class="btn btn-outline-primary w-100">邀请</button>
            </li>
        </ul>
        <el-dialog v-model="inviteWindow" top="1em">
        <div class="d-flex justify-center"><h3>用户列表</h3></div>
          <table class="table table-hover">
              <thead>
                <tr v-if="userList">
                  <th scope="col">序号</th>
                  <th scope="col">学号/学工号</th>
                  <th scope="col">姓名</th>
                  <th scope="col">类型</th>
                  <th scope="col">操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(item,index) in userLists" :key="index">
                  <th scope="row">{{ index+1 }}</th>
                  <td>{{ item.userID }}</td>
                  <td>{{ item.userName }}</td>
                  <td>{{ item.type=="stu"?"学生":"老师" }}</td>
                  <td><button @click="sendInvitation(item.userID,item.userName)">邀请</button></td>
                </tr>
              </tbody>
            </table>
        </el-dialog>
      
    </div>
  </div>
</div>
</template>

<script setup>

//先创建聊天室再邀请人加入，右侧在线人数显示，添加人以及解散聊天室，左侧下面输入信息，上部分显示聊天室信息，
import { reactive, ref,h,onUnmounted} from 'vue'
import { useRoute,useRouter } from 'vue-router';
import { ElMessage, ElMessageBox,ElNotification} from 'element-plus'
import axios from 'axios';
import { useChatwebsocketStore } from '@/store/chatwebsocket';
import moment from 'moment';

const route=useRoute()
const router=useRouter()
const activeName = ref('1')//element UI plus
let inputMessage=ref('')
let user_id=route.query.user_id
let chatroom_id=route.query.chatroom_id
let project_name=route.query.project_name
let param=user_id+"_"+chatroom_id
let admin_id=ref("")
let userList=ref([])
let inviteWindow=ref(false)
//定义一个message与后端Resultmessage对应
let sendMessage=reactive({
  system:false,
  toChatroom_id:chatroom_id,
  fromName:user_id,
  message:'',
  senderName:'',
  sendTime:""
})
  //从父组件中通过路由信息传来聊天室的ID和学生的ID

  //获取聊天室的管理员的ID
const getAdminID=async()=>{
      let result=await axios({
        method:"get",
        url:"http://localhost:8080/getLiveroomAdminID",
        params:{
          chatroom_id:chatroom_id
        }
      })
      admin_id.value=result.data
  }
 getAdminID()
//点击加入某个聊天室之后新建立一个websocket连接
//  const setConnection=()=>{
//   console.log("已经建立连接")
//     //建立一个websocket服务
//     let ws=new WebSocket("ws://localhost:8080/chat/"+param);
//     return ws
// }

//建立连接之后发送消息给其他用户
const noticeOtherUsers=()=>{
  console.log("发消息告知")
  let ws= new WebSocket("ws://localhost:8080/chat/"+param)
  console.log("建立连接之后")
  //连接建立后给其他用户发送消息告知有新的用户加入
  sendMessage.message="加入聊天室"
  sendMessage.system=true
  setTimeout(() => {
    if(ws.readyState==WebSocket.OPEN){
      ws.send(JSON.stringify(sendMessage))
    }
  }, 500);

  return ws
}

let ws =  noticeOtherUsers()

onUnmounted(()=>{
    ws.close()
})
// 为了在界面刷新的时候，已经连接的websocket连接不会被再次连接。
window.addEventListener('beforeunload',()=>{
  console.log("界面刷新之前")
  ws.close()
})

//发送按钮绑定发送消息的功能：将message对象JSON化
function sendMessageToChatroom(){
  //将用户输入的消息放进message中
  sendMessage.message=inputMessage.value
  sendMessage.system=false
  ws.send(JSON.stringify(sendMessage))
  inputMessage.value=""
}

//用来存放收到的消息
let messageListChatroom=reactive([])
  //接受到消息后将消息打印出来
  ws.onmessage=async function(evt){
    let result=JSON.parse(evt.data)
    console.log(result)
    if(result.message=="聊天室关闭" && result.system)
    {
      //如果发送的消息为“聊天室关闭”那么直接退出聊天室，并告知用户聊天室已关闭。
      ws.close()
      router.push({path:'/index/chatroom',query:{user_id:user_id}})
    }
    if(!result.system){
      console.log("进入了嘛")
      messageListChatroom.push(result)
    }
    if(result.message=="退出聊天室" && result.system){
      //弹出说明
        ElNotification({
          title: '系统消息',
          message: h('i', { style: 'color: teal' }, result.senderName+"退出了聊天室"),
        })
      //更新一下用户列表
      userList.value=await getAllUserName()
    }
    if(result.message=="加入聊天室" && result.system){
      //弹窗说明
      ElNotification({
          title: '系统消息',
          message: h('i', { style: 'color: teal' }, result.senderName+"加入聊天室"),
        })
      //更新一下用户列表
      userList.value=await getAllUserName()
    }
    if(result.message=="管理员添加了新的公告" && result.system){
        //弹窗说明
      ElNotification({
          title: '系统消息',
          message: h('i', { style: 'color: teal' }, "管理员添加了新的公告"),
        })
      //更新一下公告列表
      //添加完成后重新给noticeList赋值
      noticeList.value= await findAllNotice()
    }
  }
  ws.onclose=function(){
    console.log("聊天室websocket连接已经关闭")
  }

//根据传进来的ID判断是不是本人发送的消息
function isSelf(id){
  if(id==user_id){
    return "row mt-1 d-flex flex-row-reverse"
  }
  else{
    return "row mt-1 d-flex"
  }
}

//关闭聊天室提示窗口
const open = () => {
  ElMessageBox.confirm(
    '是否确认删除聊天室?',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      //通知其他用户聊天室关闭
      sendMessage.system=true
      sendMessage.message="聊天室关闭"
      ws.send(JSON.stringify(sendMessage))
      ws.close()
      //根据聊聊天室的ID删除选定的聊天室
      let result=await axios({
        method:"get",
        url:"http://localhost:8080/deleteChatroom",
        params:{
          chatroom_id:chatroom_id
        }
      })
      //如果成功删除的话提示用户删除成功
      if(result){
        ElMessage({
        type: 'success',
        message: 'Delete completed',
      })
      }
      //成功删除之后，聊天室解散，并转到聊天室列表界面
      router.push({path:'/index/chatroom',query:{user_id:user_id}})
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '聊天室已解散',
      })
    })
}

let noticeList=ref([])
//发送Axios请求所有的公告信息
const findAllNotice=async()=>{
  let result=await axios({
    method:"get",
    url:"http://localhost:8080/getChatroomNotice",
    params:{
      chatroom_id:chatroom_id
    }
  })
  return result.data
}
noticeList.value= await findAllNotice()
//添加公告
const dialogVisible = ref(false)
let notice=reactive({
  notice_id:"",
  notice_content:"",
  publisher_id:admin_id,
  publish_time:"",
  chatroom_id:chatroom_id
})
//点击添加公告
 async function addNoticeInChatroom(){
  let isSuccess=await axios.post("http://localhost:8080/addNoticeInChatroom",notice)
  console.log(isSuccess)
  dialogVisible.value = false
  //添加完成后重新给noticeList赋值
  noticeList.value= await findAllNotice()
  //重新给填写的公告赋值
  notice.notice_content=""
  //告知其他用户管理员添加了公告
  sendMessage.system=true
  sendMessage.message="管理员添加了新的公告"
  ws.send(JSON.stringify(sendMessage))
}
//传入指定的公告ID删除公告
async function deleteNoticeByID(notice_id){
  let result=await axios({
    method:"get",
    url:"http://localhost:8080/deleteNoticeInChatroom",
    params:{
      notice_id:notice_id
    }
  })
  if(result.data){
    //如果成功的话，重新赋值渲染
    noticeList.value= await findAllNotice()
  }
}
//获取聊天室中所有用户的ID和姓名

async function getAllUserName(){
  let result=await axios({
    method:"get",
    url:"http://localhost:8080/getAllUserName",
    params:{
      chatroom_id:chatroom_id
    }
  })
  return result.data
}


userList.value=await getAllUserName()
//退出聊天室
function exitChatroom(){
  //告知其他用户此用户已经退出聊天室
  sendMessage.message="退出聊天室"
  sendMessage.system=true
  ws.send(JSON.stringify(sendMessage))
  //关闭websocket链接
  ws.close()
  //跳转到聊天室列表界面
  router.push({path:'/index/chatroom',query:{user_id:user_id}})
}

//建立message连接，可以通过邀请老师或学生进来
//先建立websocket——message连接
let message=reactive({
  message_id:"",
  sender_id:user_id,
  send_time:"",
  receiver_id:"",
  content:"",
  system:false,
  watch:false,
  sender_name:sessionStorage.getItem("user_name"),
  receiver_name:"",
  online:false
})
const websocketStore=useChatwebsocketStore()
const getconnection=async()=>{
  let connection=new WebSocket("ws://localhost:8080/message/"+user_id);
  websocketStore.changeIsClear()
  return connection
}
let wsMessage=await getconnection()
//告知总消息处，接受到消息

wsMessage.onmessage=function(evt){
  //告知全局，数据库数据变化
  websocketStore.changeIsConnected()
   //将消息JSON化存入pinia中
   websocketStore.setMessage(JSON.parse(evt.data))
}
//获取所有的用户信息
const getAllUsers=async()=>{
  let result=await axios({
    method:"get",
    url:"http://localhost:8080/getAllUsers",
  })
  return result.data
}
let userLists=await getAllUsers()
//点击邀请，发送消息
function sendInvitation(id,name){
  message.system=true
  message.receiver_name=name
  message.receiver_id=id
  message.sender_name=sessionStorage.getItem("user_name")
  message.sender_id=admin_id
  message.content=chatroom_id
  message.send_time=moment().format('YYYY-MM-DD HH:mm:ss')
  wsMessage.send(JSON.stringify(message))
  ElMessage({
    type:'success',
    message:"邀请成功！"
  })
}

</script>

<style scoped> 

</style>